package com.mata.worktime.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mata.worktime.configuration.shiro.service.PasswordService;
import com.mata.worktime.controller.BaseController;
import com.mata.worktime.exception.BaseException;
import com.mata.worktime.vo.LayuiTableVO;
import com.mata.worktime.vo.ResultVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.mata.worktime.dto.PageParamDTO;
import com.mata.worktime.dto.UpdatePasswordDTO;
import com.mata.worktime.entity.user.Dept;
import com.mata.worktime.entity.user.Post;
import com.mata.worktime.entity.user.Role;
import com.mata.worktime.entity.user.User;
import com.mata.worktime.enums.ResultEnum;
import com.mata.worktime.service.user.DeptService;
import com.mata.worktime.service.user.PostService;
import com.mata.worktime.service.user.RoleService;
import com.mata.worktime.service.user.UserService;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 用户
 *
 * @author earthchen
 * @date 2018/9/27
 **/
@Controller
@RequestMapping("/system/user")
public class UserController extends BaseController
{

    @Autowired
    private RoleService roleService;

    @Autowired
    private PostService postService;

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordService passwordService;

    @Autowired
    private DeptService deptService;

    /**
     * 个人信息页
     *
     * @param model 模型
     * @return 个人信息页
     */
    @GetMapping("/me")
    public String me(Model model)
    {
        String userId = getUserId();
        User user = userService.getById(userId);
        model.addAttribute("user", user);
        return "user/person";
    }

    /**
     * 用户管理页
     *
     * @param model 模型
     * @return 用户管理页
     */
    @RequiresPermissions("system:user:view")
    @GetMapping("/view")
    public String user(Model model)
    {
        List<Post> postList = postService.selectPostAll();
        List<Role> roleList = roleService.selectRoleAll();
        model.addAttribute("postList", postList);
        model.addAttribute("roleList", roleList);
        return "user/user";
    }

    /**
     * 新增用户页面
     *
     * @param mmap 模型
     * @return 新增用户页面
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        mmap.put("roles", roleService.selectRoleAll());
        mmap.put("posts", postService.selectPostAll());
        return "user/add";
    }

    /**
     * 新增保存用户
     *
     * @param user 用户信息
     * @return 统一结果
     */
    @RequiresPermissions("system:user:add")
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public ResultVO addSave(@Valid User user)
    {
        List<User> userList = userService.list(new QueryWrapper<User>()
            .eq("login_name", user.getLoginName())
            .eq("del_flag", 0)
        );
        if (null != userList && userList.size() > 0)
        {
            throw new BaseException(ResultEnum.USER_ALREADY_EXISTS);
        }

        if (user.getUserId() != null && User.isAdmin(user.getUserId()))
        {
            return ResultVO.error(1, "不允许修改超级管理员用户");
        }
        userService.saveUser(user);
        return ResultVO.success();
    }

    /**
     * 修改用户页面
     *
     * @param userId 用户id
     * @param mmap   模型
     * @return 更新页面
     */
    @GetMapping("/update/{userId}")
    public String edit(@PathVariable("userId") String userId, ModelMap mmap)
    {
        User user = userService.getById(userId);
        Dept dept = deptService.selectDeptById(Long.valueOf(user.getDeptId()));
        user.setDept(dept);
        mmap.put("user", user);
        mmap.put("roleList", roleService.selectRolesByUserId(userId));
        mmap.put("postList", postService.selectPostsByUserId(userId));
        return "user/update";
    }

    /**
     * 重置密码页面
     *
     * @param userId 用户id
     * @param mmap   模型
     * @return 重置密码页面
     */
    @RequiresPermissions("system:user:resetPwd")
    @GetMapping("/resetPwd/{userId}")
    public String resetPwd(@PathVariable("userId") Long userId, ModelMap mmap)
    {
        mmap.put("user", userService.getById(userId));
        return "user/resetPwd";
    }

    /**
     * 重置密码接口
     *
     * @param user 用户信息
     * @return 统一结果
     */
    @RequiresPermissions("system:user:resetPwd")
    @PostMapping("/resetPwd")
    @ResponseBody
    public ResultVO resetPwd(User user)
    {
        userService.resetUserPwd(user);
        return ResultVO.success();
    }

    /**
     * 删除用户
     * <p>
     * 根据id
     *
     * @param ids 多个id的字符串
     * @return 统一结果
     */
    @RequiresPermissions("system:user:remove")
    @PostMapping("/del")
    @ResponseBody
    public ResultVO remove(String ids)
    {
        userService.deleteUserByIds(ids);
        return ResultVO.success();
    }

    /**
     * 分页获取用户信息
     *
     * @param pageParamDTO 分页参数
     * @param userName     用户名
     * @param loginName    登录名
     * @return 用户信息列表
     */
    @RequiresPermissions("system:user:list")
    @GetMapping("/list")
    @ResponseBody
    public LayuiTableVO list(PageParamDTO pageParamDTO, String userName, String loginName)
    {
        List<String> fileds = new ArrayList<>();
        fileds.add("create_time");
        fileds.add("update_time");
        IPage<User> page = new Page<User>(pageParamDTO.getPage(), pageParamDTO.getSize()).setDescs(
            fileds);
        page = userService.page(page, new QueryWrapper<User>()
            .ne("user_name", "admin")
            .eq("del_flag", "0")
            .like(StringUtils.isNotBlank(userName), "user_name", userName)
            .like(StringUtils.isNotBlank(loginName), "login_name", loginName));
        return getTableInfo(page);
    }

    /**
     * 删除指定id的用户
     *
     * @param userId 用户id
     * @return 统一结果
     */
    @DeleteMapping("/del/{userId}")
    @ResponseBody
    public ResultVO del(@PathVariable("userId") Long userId)
    {
        User user = userService.getById(userId);
        //删除状态
        user.setDelFlag("1");
        return ResultVO.success(userService.updateById(user));
    }

    /**
     * 修改用户
     *
     * @param user   用户信息
     * @param userId 用户id
     * @return 统一结果
     */
    @RequiresPermissions("system:user:edit")
    @PutMapping("/update/{userId}")
    @ResponseBody
    public ResultVO update(@PathVariable("userId") String userId, User user)
    {
        user.setId(userId);
        if (user.getUserId() != null && User.isAdmin(user.getUserId()))
        {
            return ResultVO.error(1, "不允许修改超级管理员用户");
        }
        List<User> userList = userService.list(new QueryWrapper<User>()
            .eq("login_name", user.getLoginName())
            .eq("del_flag", 0)
            .ne("id",userId)
        );
        if (null != userList && userList.size() > 0)
        {
            throw new BaseException(ResultEnum.USER_ALREADY_EXISTS);
        }
        // 修改岗位 角色
//        userService.updateUser(user);
//        return ResultVO.success(userService.updateById(user));
        return ResultVO.success(userService.updateUser(user));
    }

    /**
     * 管理员重置密码123456
     *
     * @param userId 用户id
     * @return 统一结果
     */
    @RequiresPermissions("system:user:resetPwd")
    @PutMapping("/reset/{userId}")
    @ResponseBody
    public ResultVO resetPassword(@PathVariable("userId") Long userId)
    {
        // 如果不是管理员 抛异常
        if (!getUser().isAdmin())
        {
            throw new BaseException(ResultEnum.RESET_PASSWORD_ONLY_ADMIN);
        }
        User user = userService.getById(userId);
        user.setUpdateBy(getUser().getLoginName());
        user.setUpdateTime(new Date());
        user.setPassword("123456");
        userService.resetUserPwd(user);
        return ResultVO.success();
    }

    /**
     * 修改密码
     *
     * @return 修改密码页面
     */
    @GetMapping("/password")
    public String password()
    {
        return "user/password";
    }

    /**
     * 只能本人修改自己的密码
     *
     * @param updatePasswordDTO 修改密码的请求参数
     * @return 统一返回结果
     */
    @ResponseBody
    @PutMapping("/password")
    public ResultVO updatePassword(@Valid UpdatePasswordDTO updatePasswordDTO)
    {
        String oldPassword = passwordService.encryptPassword(getLoginName(),
            updatePasswordDTO.getOldPassword(), getUser().getSalt());
        if (!oldPassword.equals(getUser().getPassword()))
        {
            throw new BaseException();
        }
        User user = new User();
        user.setId(getUserId());
        user.setLoginName(getLoginName());
        user.setUpdateBy(getUser().getLoginName());
        user.setUpdateTime(new Date());
        user.setPassword(updatePasswordDTO.getNewPassword());
        userService.resetUserPwd(user);
        return ResultVO.success();
    }

}
